import qs from 'qs'
import { Message } from 'element-ui'
import router from '@/router'
import store from '@/store'

import axios from 'axios'

axios.defaults.headers.post['Content-Type'] =
	'application/x-www-form-urlencoded;charset=UTF-8'
// 创建axios实例

const service = axios.create({
	baseURL: '/api', // api 的 base_url
	timeout: 600000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(
	async (config) => {
		const flag =
			config.headers['Content-Type']?.indexOf('application/json') !== -1
		if (!flag) {
			const mult =
				config.headers['Content-Type']?.indexOf('multipart/form-data') !== -1
			if (mult) {
				config.data = config.data
			} else {
				config.data = qs.stringify(config.data)
			}
		}
		if (store.getters.token) {
			config.headers['Business-Token'] = store.getters.token
		}

		return config
	},

	(error) => {
		Message({
			message: '啊哦，服务器飞到外太空了~',
			type: 'error'
		})
		return Promise.reject(error)
	}
)

// response 拦截器
service.interceptors.response.use(
	(response) => {
		const res = response.data
		if (response.status === 200 && response.config.responseType === 'blob') {
			// 文件类型特殊处理
			return response
		} else if (res.code == 302) {
			router.push('/login')
			return Promise.reject(res)
		} else if (res.code == 0) {
			return res
		} else {
			if (res.msg) {
				if (response.config.remind !== false) {
					const { toastProps = {} } = response.config
					Message({
						message: res.msg,
						type: 'error',
						...toastProps
					})
				}
			}
			return Promise.reject(res)
		}
	},
	(error) => {
		if (error.config.remind !== false) {
			const { toastProps = {} } = error.config
			Message({
				message: '啊哦，服务器飞到外太空了~',
				type: 'error',
				...toastProps
			})
		}
		console.error(error)
		return Promise.reject(error)
	}
)

export default service
